﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DatabaseComponent;
using System.Web.SessionState;
using System.IO;

using System.Web.Configuration;
using System.Configuration;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web.UI.WebControls;
using System.Net;
using System.Threading;
using System.Web.Security;


/// <summary>
/// Summary description for GlobalVars
/// </summary>
public class GlobalVars
{


    public static Thread thSendAllMailsThread = null;

    /// <summary>
    /// this function will send the family mails
    /// </summary>
    public static void sendFamilyMails()
    {

        if (thSendAllMailsThread != null)
        {
            if (thSendAllMailsThread.ThreadState == ThreadState.Running)
                return;
            else
            {
                try
                {
                    thSendAllMailsThread.Abort();
                }
                catch
                {
                }
            }
        }

        thSendAllMailsThread = new Thread(sendFamilyMailsThread);

        thSendAllMailsThread.Start();

    }



    protected static void sendFamilyMailsThread()
    {
        List<Persons> lstPersons = new List<Persons>();
        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);

        lstPersons = objPersonsDB.Select("", " where [ID] = '' ");

        foreach (Persons objEmp in lstPersons)
        {


            string strMail = "";

            strMail = objEmp.Email;

            List<object> lstParams = new List<object>();

            string strTitle = "\"ILearn\" System ";

            string strBody = "Dear Employee \"" + objEmp.getFullName() + "\" <br /> ";
            strBody += "Find Below Login Details To \"ILearn\" System For Your Family : <br />";

            string strFamilyTable = "";

            strFamilyTable += "<table><tr><td>Arabic Name</td><td>English Name</td><td>Relation</td><td>User</td><td>Password</td></tr>";

            bool hasFamily = false;
            foreach (Persons objPer in objEmp.lstFamily)
            {
                hasFamily = true;

                strFamilyTable += "<tr><td>" + objPer.getFullNameAR() + "</td><td>" + objPer.getFullName() + "</td><td>" + objPer.objRelation.RelationNameAR + "</td><td>" + objPer.ID + "</td><td>1234</td></tr>";


            }



            strFamilyTable += "</table><br />";


            strBody += strFamilyTable;
            strBody += "Your Family Must Change Thier Passwords And Add Thier Emails By Click Profile Tab Then Click Edit. ";

            lstParams.Add(strTitle);
            lstParams.Add(strBody);
            lstParams.Add(strMail);
            lstParams.Add(getEmailData());


            if (hasFamily)
                SendRequestMailThread(lstParams);
        }
    }





    public static string buildMailBody(string strBody, bool isRtl)
    {
        string strRet = "";
        strRet = "<table style='font-size:14px;width:100%;direction:"+ (isRtl?"rtl;":"ltr;") +"text-align:" + (isRtl?"right;":"left;") + "' cellpadding='0' cellspaceing='0'>\r\n<tr>\r\n<td style='width:100%;'>";

        strRet += strBody;

        strRet += "</td>\r\n</tr>\r\n</table>";


        return strRet;
    }


    /// <summary>
    /// this function will send a mail to the user with its status
    /// </summary>
    /// <param name="objReg">the registered courses object</param>
    /// <param name="objPer">the user</param>
    /// <param name="status">the status (1,2,3,4)</param>
    public static void sendLogMail(RegisteredCourses objReg, Persons objPer, long status)
    {
        string strMessageAR = "";
       
        string strMessageEN = "";
        string strTitleEN = "";

        switch (status)
        {
            case 1 :
                
               
                strMessageAR = "عزيزي المستخدم تم تسجيلك في الدورة الالكترونية " + objReg.objCourses.CourseNameAR + " بنجاح في نظام \"أنا أتعلم\" ";
                strMessageAR = buildMailBody(strMessageAR, true);
                strTitleEN = "Enrollment in Electronic course ";
                strMessageEN = "Dear user you have successfully enrolled in electronic course " + objReg.objCourses.CourseNameEN + " in \"iLearn\" system. ";
                strMessageEN = buildMailBody(strMessageEN, false);
                break;
           
            case 4 :
                 
                strMessageAR = "عزيزي المستخدم تم اجتيازك لدورة  " + objReg.objCourses.CourseNameAR + " الالكترونية بنجاح في نظام \"أنا أتعلم\" ";
                strMessageAR = buildMailBody(strMessageAR, true);
                strTitleEN = "Electronic Course Completed";
                strMessageEN = "Dear user you have successfully completed the electronic course  " + objReg.objCourses.CourseNameEN + " in \"iLearn\" system. ";
                strMessageEN = buildMailBody(strMessageEN, false);
                break;
            default:
                return;
                break;
        }


        
        GlobalVars.SendRequestMail(strTitleEN, strMessageEN + "<br /><br />" + strMessageAR , objPer.Email);

    }


    /// <summary>
    /// this method will create a hard copy from every mail message sent by system
    /// </summary>
    /// <param name="strTitle">the title of the message</param>
    /// <param name="strBody">the body of the message</param>
    /// <param name="MailAddress">the mail address</param>
    public static void writeMailFile(string strTitle, string strBody, string MailAddress)
    {
        try
        {
            if (!Directory.Exists("C:\\LmsMailBackup"))
            {
                Directory.CreateDirectory("C:\\LmsMailBackup");
            }

            string FileName = "C:\\LmsMailBackup\\" + MailAddress + "_" + System.Guid.NewGuid().ToString() + ".txt";

            System.IO.File.WriteAllText(FileName, strTitle + "\r\n" + strBody);
        }
        catch
        {
        }
    }



    /// <summary>
    /// this function will get the registered refreshed with fail status
    /// </summary>
    /// <param name="rc">the registered to set</param>
    public static void CustomizeRegisterForFail(RegisteredCourses rc)
    {
        UserLogsDB objUserLogsDB = new UserLogsDB(ConnectionStrings.LMS);
        List<UserLogs> lstUserLogs = objUserLogsDB.getUserLogsByRegisteredCoursesID(rc.ID);

        


        if (lstUserLogs.Count < 4)
            return;


        lstUserLogs = new List<UserLogs>(from obj in lstUserLogs orderby obj.CurrentDate descending select obj );



        int nCount = 0;

        if (lstUserLogs[0].Status != 3)
            return;


        foreach (UserLogs obj in lstUserLogs)
        {
            if (obj.Status == 4)
                return;

            if (obj.Status == 2)
                return;

            if (obj.Status == 3)
                nCount++;

            if (nCount == 3)
            {
               
                rc.CourseStatus = (long)CourseEnum.Learning;
                                
                refreshRegistered(rc);
                return;

            }
        }
        
        
        
    }


    /// <summary>
    /// this function will set Registered as first time
    /// </summary>
    /// <param name="rc">the registered to set</param>
    public static void refreshRegistered(RegisteredCourses rc)
    {
        //rc.CurrentData = "";
        //rc.LastSlide = 0;
       
        //RegisteredCoursesDB objRegisteredCoursesDB = new RegisteredCoursesDB(ConnectionStrings.LMS);



        //objRegisteredCoursesDB.Update(rc);

        CoursesScoesDB objCoursesScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);

        List<CoursesScoes> lstDeletedScoes = rc.lstCoursesScoes;

        foreach (CoursesScoes obj in lstDeletedScoes)
        {
            obj.ScoData = "";
            obj.IsCompleted = false;
            objCoursesScoesDB.Update(obj);
        }


    }



   
    
    /// <summary>
    /// this function will get the not captivate grid values to grid
    /// </summary>
    /// <param name="objCourses">the current course</param>
    /// <param name="currentPerson">the current user</param>
    /// <param name="lblSpendTime">the total spend time label to set</param>
    /// <param name="pnlStart">the panel to set</param>
    /// <param name="lblCourseStatus">The course status to set</param>
    public static void CustomizeGridNotCaptivate(Courses objCourses, Persons currentPerson, Label lblSpendTime, Panel pnlStart, Label lblCourseStatus,bool isArabic)
    {

        string strResumeCourse = isArabic ? "تكملة الدورة" : "Resume course";
        string strLaunchCourse = isArabic ? "بدء الدورة" : "Launch Course";
        string strPressHereToStart = isArabic ? "اضغط هنا لبدء الدورة" : "Press here to start learning.";
        string strInProcess = isArabic ? "قيد الاستخدام" : "In process";
        string strNotYetStarted = isArabic ? "لم تبدأ بعد" : "Not yet started";
        string strLaunchExam = isArabic ? "بدء الاختبار" : "Launch exam";
        string strWaitForExam = isArabic ? "انتظار اجتياز الاختبار" : "Wait for exam";
        string strCompleted = isArabic ? "مكتملة" : "Completed";
        string strPrintCert = isArabic ? "طباعة الشهادة " : "Print certification ";
        string strPrintCertMessage = isArabic ? "اضغط هنا لطباعة الشهادة." : "Press here to print a certification.";
        string strStartExamMessage = isArabic ? "اضغط هنا لبدء الاختبار" : "Press here to start the exam.";
        string exampage = isArabic ? "start_examAR.aspx" : "start_examEN.aspx";
        string restartName = isArabic ? "ابدأ من جديد" : "Launch again";

        foreach (RegisteredCourses obj in currentPerson.lstRegisteredCourses)
        {
            if (obj.CoursesID == objCourses.ID)
            {


                bool isAllCompleted = true;

                List<CoursesScoes> lstAllScoes = obj.lstCoursesScoes;

                foreach (CoursesScoes objSco in lstAllScoes)
                {
                    if (!objSco.IsCompleted)
                    {
                        isAllCompleted = false;
                        break;
                    }
                }


                

                List<FinishedExams> lstFinished = GlobalVars.getAllSucceedFinishedExam(obj.ID);


                if (obj.TotalSpendTime > 0)
                    lblSpendTime.Text = GlobalVars.setSecounds(obj.TotalSpendTime);
                else
                    lblSpendTime.Text = "00:00:00";


               



                switch (obj.CourseStatus)
                {
                    case (long)CourseEnum.Learning:
                        {

                            HyperLink hl = new HyperLink();
                            hl.NavigateUrl = "start_learn_frame.aspx?id=" + objCourses.ID.ToString();

                            if (obj.TotalSpendTime <= 0)
                                hl.Text = strLaunchCourse;
                            else
                                hl.Text = strResumeCourse;


                            //hl.Target = "_blank";
                            hl.ToolTip = strPressHereToStart;
                            hl.Target = "_blank";
                            pnlStart.Controls.Add(hl);


                            if (obj.TotalSpendTime > 0)
                                lblCourseStatus.Text = strInProcess;
                            else
                                lblCourseStatus.Text = strNotYetStarted;



                        }






                        break;

                    case (long)CourseEnum.Waiting_exam:
                        {

                            HyperLink hl = new HyperLink();
                            hl.NavigateUrl = "start_learn_frame.aspx?id=" + objCourses.ID.ToString();

                            if (obj.TotalSpendTime <= 0)
                                hl.Text = strLaunchCourse;
                            else
                                hl.Text = strResumeCourse;


                            //hl.Target = "_blank";
                            hl.ToolTip = strPressHereToStart;
                            hl.Target = "_blank";
                            pnlStart.Controls.Add(hl);


                            Literal ltNew = new Literal();
                            ltNew.Text = "<br /><br />";

                            pnlStart.Controls.Add(ltNew);


                            hl = new HyperLink();
                            
                                hl.NavigateUrl = exampage +  "?id=" + objCourses.ID.ToString();
                            


                            hl.Text = strLaunchExam;


                            //hl.Target = "_blank";
                            hl.ToolTip = strStartExamMessage;
                            pnlStart.Controls.Add(hl);


                            lblCourseStatus.Text = strWaitForExam;


                        }
                        break;

                    case  (long)CourseEnum.Completed:
                        {
                            if (!isAllCompleted)
                            {
                                HyperLink hl = new HyperLink();
                                hl.NavigateUrl = "start_learn_frame.aspx?id=" + objCourses.ID.ToString();


                                hl.Text = strLaunchCourse;



                                //hl.Target = "_blank";
                                hl.ToolTip = strPressHereToStart;
                                hl.Target = "_blank";
                                pnlStart.Controls.Add(hl);


                                

                            }
                            else
                            {
                                LinkButton lnkRestart = pnlStart.FindControl("lnkRestart") as LinkButton;

                                if (lnkRestart != null)
                                {
                                    lnkRestart.Visible = true;
                                   
                                }

                            }

                            lblCourseStatus.Text = strCompleted;

                            

                        }

                        break;


                }




                FinishedExams fe = new FinishedExams();
                bool bFound = false;
                foreach (FinishedExams fe1 in lstFinished)
                {
                    if (!bFound)
                    {
                        bFound = true;
                        fe = fe1;
                    }
                    else
                    {
                        if (fe.CurrentDate < fe1.CurrentDate)
                        {
                            fe = fe1;

                        }
                    }
                }

                if (bFound)
                {
                    Literal ltNew = new Literal();
                    ltNew.Text = "<br /><br />";

                    pnlStart.Controls.Add(ltNew);


                    HyperLink hl = new HyperLink();
                    hl.NavigateUrl = "print_cert.aspx?id=" + fe.ID;


                    hl.Text = strPrintCert + fe.CurrentDate.ToString("dd/MM/yyyy");


                    //hl.Target = "_blank";
                    hl.ToolTip = strPrintCertMessage;
                    hl.Target = "_blank";
                    pnlStart.Controls.Add(hl);
                }

               




                
                    
                



               

               

                    

               


                



                #region switchCommented
                //switch (obj.CourseStatus)
                //{
                //    case (long)CourseEnum.Completed:
                //        {
                //            lblCourseStatus.Text = "Completed";

                //            HyperLink hl = new HyperLink();
                //            hl.NavigateUrl = "print_certificate.aspx?perid=" + currentPerson.GenID.ToString() + "&corid=" + objCourses.ID.ToString();
                //            hl.Text = "Print certificate";
                //            hl.ToolTip = "Print a certificate of completing this course sucessfully.";
                //            hl.Target = "_blank";
                //            pnlStart.Controls.Add(hl);
                //            break;
                //        }
                //    case (long)CourseEnum.Exam_fail:
                //        {

                //            lblCourseStatus.Text = "Failed in exam";

                //            HyperLink hl = new HyperLink();
                //            hl.NavigateUrl = "start_learn.aspx?id=" + objCourses.ID.ToString();

                //            hl.Text = "Start course again";

                //            //hl.Target = "_blank";

                //            hl.ToolTip = "Press here to start learning.";
                //            pnlStart.Controls.Add(hl);

                //            break;
                //        }

                //    case (long)CourseEnum.Learning:
                //        {
                //            lblCourseStatus.Text = "Learning";

                //            HyperLink hl = new HyperLink();
                //            hl.NavigateUrl = "start_learn.aspx?id=" + objCourses.ID.ToString();

                //            if (obj.TotalSpendTime <= 0)
                //                hl.Text = "Start course";
                //            else
                //                hl.Text = "Resume course";


                //            //hl.Target = "_blank";
                //            hl.ToolTip = "Press here to start learning.";
                //            pnlStart.Controls.Add(hl);
                //            break;
                //        }

                //    case (long)CourseEnum.Waiting_exam:
                //        {
                //            lblCourseStatus.Text = "Waiting for exam";

                //            HyperLink hl = new HyperLink();
                //            hl.NavigateUrl = "start_exam.aspx?id=" + objCourses.ID.ToString();


                //                hl.Text = "Start exam";


                //                hl.Target = "_blank";

                //            hl.ToolTip = "Press here to start the exam.";
                //            pnlStart.Controls.Add(hl);

                //            Literal lt = new Literal();
                //            lt.Text = "<br />";

                //            pnlStart.Controls.Add(lt);

                //            hl = new HyperLink();
                //            hl.NavigateUrl = "start_learn.aspx?id=" + objCourses.ID.ToString() + "&restart=true";

                //            if (obj.LastSlide == (obj.TotalSlides - 1))
                //                hl.Text = "Restart the course";
                //            else
                //                hl.Text = "Resume";


                //            //hl.Target = "_blank";

                //            hl.ToolTip = "Press here to start learning.";
                //            pnlStart.Controls.Add(hl);


                //            break;
                //        }
                //    default:
                //        lblCourseStatus.Text = "Error";
                //        Label lblPanel = new Label();
                //        lblPanel.Text = "Error";
                //        pnlStart.Controls.Add(lblPanel);

                //        break;
                //}
                #endregion


                break;
            }
        }
    }



    /// <summary>
    /// this function will get the captivate grid values to grid
    /// </summary>
    /// <param name="objCourses">the current course</param>
    /// <param name="currentPerson">the current user</param>
    /// <param name="lblSpendTime">the total spend time label to set</param>
    /// <param name="pnlStart">the panel to set</param>
    /// <param name="lblCourseStatus">The course status to set</param>
    public static void CustomizeGrid(Courses objCourses, Persons currentPerson, Label lblSpendTime, Panel pnlStart, Label lblCourseStatus,bool isArabic)
    {
        CustomizeGridNotCaptivate(objCourses, currentPerson, lblSpendTime, pnlStart, lblCourseStatus, isArabic);
        return;
        string strResumeCourse = isArabic ? "تكملة الدورة" : "Resume course";
        string strLaunchCourse = isArabic ? "بدء الدورة" : "Launch Course";
        string strPressHereToStart = isArabic ?  "اضغط هنا لبدء الدورة" : "Press here to start learning." ;
        string strInProcess = isArabic ? "قيد الاستخدام" : "In process";
        string strNotYetStarted = isArabic ? "لم تبدأ بعد" : "Not yet started";
        string strLaunchExam = isArabic ? "بدء الاختبار" : "Launch exam";
        string strWaitForExam = isArabic ? "انتظار اجتياز الاختبار" : "Wait for exam";
        string strCompleted = isArabic ? "مكتملة" : "Completed";
        string strPrintCert = isArabic ? "طباعة الشهادة " : "Print certification ";
        string strPrintCertMessage = isArabic ? "اضغط هنا لطباعة الشهادة." : "Press here to print a certification.";
        string strStartExamMessage = isArabic ? "اضغط هنا لبدء الاختبار" : "Press here to start the exam.";


        foreach (RegisteredCourses obj in currentPerson.lstRegisteredCourses)
        {
            if (obj.CoursesID == objCourses.ID)
            {



                if (obj.TotalSpendTime > 0)
                    lblSpendTime.Text = GlobalVars.setSecounds(obj.TotalSpendTime);
                else
                    lblSpendTime.Text = "00:00:00";

                List<FinishedExams> lstFinished = GlobalVars.getAllSucceedFinishedExam(obj.ID);



                switch (obj.CourseStatus)
                {
                    case (long)CourseEnum.Learning:
                        {

                            HyperLink hl = new HyperLink();
                            hl.NavigateUrl = "start_learn.aspx?id=" + objCourses.ID.ToString();


                            if (obj.TotalSpendTime > 0)
                                hl.Text = strResumeCourse;
                            else
                                hl.Text = strLaunchCourse;


                            hl.Target = "_blank";

                            hl.ToolTip = strPressHereToStart;
                            pnlStart.Controls.Add(hl);



                            if (obj.TotalSpendTime > 0)
                                lblCourseStatus.Text = strInProcess;
                            else
                                lblCourseStatus.Text = strNotYetStarted;
                        }



                      break;

                    case (long)CourseEnum.Waiting_exam:
                        {

                            HyperLink hl = new HyperLink();
                            hl.NavigateUrl = "start_learn.aspx?id=" + objCourses.ID.ToString();


                            if (obj.TotalSpendTime > 0)
                                hl.Text = strResumeCourse;
                            else
                                hl.Text = strLaunchCourse;


                            hl.Target = "_blank";

                            hl.ToolTip = strPressHereToStart;
                            pnlStart.Controls.Add(hl);



                            Literal ltNew = new Literal();
                            ltNew.Text = "<br /><br />";
                            pnlStart.Controls.Add(ltNew);




                            hl = new HyperLink();
                            hl.NavigateUrl = "start_exam.aspx?id=" + objCourses.ID.ToString();


                            hl.Text = strLaunchExam;


                            hl.Target = "_blank";

                            hl.ToolTip = strStartExamMessage;
                            pnlStart.Controls.Add(hl);







                         lblCourseStatus.Text = strWaitForExam;


                        }
                        break;

                    case (long)CourseEnum.Completed:
                        {

                            HyperLink hl = new HyperLink();
                            hl.NavigateUrl = "start_learn.aspx?id=" + objCourses.ID.ToString();


                           
                                hl.Text = strLaunchCourse;


                            hl.Target = "_blank";

                            hl.ToolTip = strPressHereToStart;
                            pnlStart.Controls.Add(hl);


                            lblCourseStatus.Text = strCompleted;




                        }

                        break;


                }



                FinishedExams fe = new FinishedExams();
                bool bFound = false;
                foreach (FinishedExams fe1 in lstFinished)
                {
                    if (!bFound)
                    {
                        bFound = true;
                        fe = fe1;
                    }
                    else
                    {
                        if (fe.CurrentDate < fe1.CurrentDate)
                        {
                            fe = fe1;

                        }
                    }
                }

                if (bFound)
                {
                    Literal ltNew = new Literal();
                    ltNew.Text = "<br /><br />";

                    pnlStart.Controls.Add(ltNew);


                    HyperLink hl = new HyperLink();
                    hl.NavigateUrl = "print_cert.aspx?id=" + fe.ID;


                    hl.Text = strPrintCert + fe.CurrentDate.ToString("dd/MM/yyyy");


                    //hl.Target = "_blank";
                    hl.ToolTip = strPrintCertMessage;
                    hl.Target = "_blank";
                    pnlStart.Controls.Add(hl);

                   
                }

                break;
            }



                
                            

                            

                            


                                


        }
    }


    /// <summary>
    /// this function will get the directory of the course in our CourseFilesFolder
    /// </summary>
    /// <param name="objCourses">The course to get its path</param>
    /// <returns>a string containing the course path</returns>
    public static string getCoursePath(Courses objCourses)
    {
        HttpServerUtility Server = HttpContext.Current.Server;

        string strFileName = "./CourseFiles/" + objCourses.Path;

        FileInfo fi = new FileInfo(Server.MapPath(strFileName));

        return fi.FullName.Substring(0, fi.FullName.Length - fi.Extension.Length) + "\\";

    }


    /// <summary>
    /// this function will send an email of the sended request
    /// </summary>
    /// <param name="tc">the ticket created by the request</param>
    public static void SendRequestMail(string strTitle,string strBody,string emailAddress)
    {


        List<object> lstParams = new List<object>();
        lstParams.Add(strTitle);
        lstParams.Add(strBody);
        lstParams.Add(emailAddress);
        lstParams.Add(getEmailData());



        Thread thNew = new Thread(new ParameterizedThreadStart(SendRequestMailThread));

        thNew.Start((object)lstParams);        

    }

    public static void SendRequestMailThread (object objParams)
    {

       


        

        string strTitle; string strBody; string emailAddress;

        


        try
        {
            List<object> lstParams = (List<object>)objParams;
            strTitle = lstParams[0].ToString();
            strBody = lstParams[1].ToString();
            emailAddress = lstParams[2].ToString();
            EmailData ed = lstParams[3] as EmailData;
            Regex reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

            if ((!emailAddress.Equals(String.Empty)) && reg.IsMatch(emailAddress))
            {
                //writeMailFile(strTitle, strBody, emailAddress);

                 

                SmtpClient sc = new SmtpClient(ed.hostServer, ed.portNumber);

                if (!ed.Username.Equals(String.Empty))
                {
                    sc.EnableSsl = true;

                    sc.DeliveryMethod = SmtpDeliveryMethod.Network;

                    sc.Credentials = new System.Net.NetworkCredential(ed.Username, ed.Password);
                }



                MailMessage mm = new MailMessage();
                mm.Subject = strTitle;
                mm.Body = strBody;
                //File.WriteAllText("c:\\1.html",  strBody );
                mm.IsBodyHtml = true;


                mm.To.Add(new MailAddress(emailAddress));

                mm.From = new MailAddress(ed.senderMail);

                sc.Send(mm);
            }
        }
        catch
        { }


    }

    /// <summary>
    /// this function will get all email data from web config
    /// </summary>
    /// <returns></returns>
    public static EmailData getEmailData()
    {
        //try
        //{
        //    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        //    EmailData ed = (EmailData)config.GetSection("emailData");

        //    return ed;
        //}
        //catch
        //{

        EmailData ed;
        


            try
            {

                try
                {
                   ed = HttpContext.Current.Application["emailData"] as EmailData ;
                    if (ed != null)
                        return ed;
                }
                catch
                {
                }

                 ed = new EmailData();
                ed.hostServer = WebConfigurationManager.AppSettings["hostServer"];
                ed.portNumber = int.Parse (WebConfigurationManager.AppSettings["portNumber"]);
                ed.senderMail = getSenderMail();
                //ed.senderMail = WebConfigurationManager.AppSettings["senderMail"];
                ed.Username = WebConfigurationManager.AppSettings["Username"];
                ed.Password = WebConfigurationManager.AppSettings["Password"];

                try
                {
                    HttpContext.Current.Application["emailData"] = ed;
                }
                catch
                {
                }
                                                      
                   
                

                return ed;
            }
            catch
            {
                return new EmailData ();
            }
        //}

    }


    /// <summary>
    /// this function will read database and get sender mail
    /// </summary>
    /// <returns>the mail to get</returns>
    public static string getSenderMail()
    {
        SupportMainMailDB objDB = new SupportMainMailDB(ConnectionStrings.LMS);
        List<SupportMainMail> lst = objDB.Select("", "");
        if (lst.Count == 0)
            return "hrd-elearning@se.com.sa";
        else
            return lst[0].Email;



    }



    /// <summary>
    /// this function will get the Virtual directory of the course in our CourseFilesFolder
    /// </summary>
    /// <param name="objCourses">The course to get its path</param>
    /// <returns>a string containing the course path</returns>
    public static string getCourseVirtualPath(Courses objCourses)
    {
        HttpServerUtility Server = HttpContext.Current.Server;

        string strFileName = "./CourseFiles/" + objCourses.Path;

        FileInfo fi = new FileInfo(Server.MapPath(strFileName));

        string FolderName = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);


        return "./CourseFiles/" + FolderName + "/";

    }



    /// <summary>
    /// this function will get all Exams that the person succeded in it
    /// </summary>
    /// <param name="RegisteredCoursesID">the registered course that we will get its exams</param>
    public static List<FinishedExams> getAllSucceedFinishedExam(long RegisteredCoursesID)
    {
        FinishedExamsDB objFinishedExamsDB = new FinishedExamsDB(ConnectionStrings.LMS);
        List<FinishedExams> lstFinishedExams = objFinishedExamsDB.Select("", " where [RegisteredCoursesID] = '" + RegisteredCoursesID + "' AND [Degree] >= 75 ");
        return lstFinishedExams;
        
    }




    /// <summary>
    /// this function will add a finished exam , may be succeed in it or fail in it , it determines by its degree
    /// </summary>
    /// <param name="RegisteredCoursesID">the registered course to add exam to </param>
    /// <param name="ExamIDs">the ids of the questions asked in that exam</param>
    /// <param name="Answers">1 or 0 , 1 for true answer and 0 for false</param>
    /// <param name="Degree">the degree of the overall exam</param>
    public static void addFinishedExam(long RegisteredCoursesID, string ExamIDs, string Answers, double Degree)
    {
        FinishedExamsDB objFinishedExamsDB = new FinishedExamsDB(ConnectionStrings.LMS);

        FinishedExams objFininshed = new FinishedExams();
        objFininshed.Degree = Degree;
        objFininshed.RegisteredCoursesID = RegisteredCoursesID;
        objFininshed.Answers = Answers;
        objFininshed.CurrentDate = DateTime.Now;
        objFininshed.ExamIDs = ExamIDs;
        objFinishedExamsDB.Insert(objFininshed);
    }




    /// <summary>
    /// this function will add a log of what user doing
    /// </summary>
    /// <param name="RegisteredCoursesID">the registered course to add log to</param>
    /// <param name="status">the status that happened at this log</param>
    public static void addLog(long RegisteredCoursesID,long status)
    {
        UserLogsDB objUserLogsDB = new UserLogsDB(ConnectionStrings.LMS);
        UserLogs objUserLogs = new UserLogs();

        objUserLogs.RegisteredCoursesID = RegisteredCoursesID;
        objUserLogs.CurrentDate = DateTime.Now;
        objUserLogs.Status = status;

        objUserLogsDB.Insert(objUserLogs);
    }



    /// <summary>
    /// this function will randomize the list order
    /// </summary>
    /// <param name="lstCurrentQuestions">the list to randomize</param>
    /// <returns>a new list with result</returns>
    public static List<Questions> RandomizeList(List<Questions> lstCurrentQuestionsIn)
    {
        List<Questions> lstCurrentQuestions = new List<Questions>();
        lstCurrentQuestions.AddRange(lstCurrentQuestionsIn.ToArray());


        List<Questions> lstRet = new List<Questions>();

        long count = lstCurrentQuestions.Count;


        while (lstRet.Count < count)
        {
            Random rnd = new Random((int)DateTime.Now.ToBinary());
            int i = rnd.Next(0, lstCurrentQuestions.Count - 1);

            lstRet.Add(lstCurrentQuestions[i]);

            lstCurrentQuestions.RemoveAt(i);


        }


        return lstRet;
        
    }

    /// <summary>
    /// this function will check if the user on the domain and if it's it will check the its user name and get the person from db
    /// </summary>
    public static void setPersonsInSession()
    {
        //File.WriteAllText ("c:\\user.txt",HttpContext.Current.User.Identity.Name);
        //HttpContext.Current.User = new System.Security.Principal.WindowsPrincipal (new System.Security.Principal.WindowsIdentity(

        string Username = HttpContext.Current.User.Identity.Name;

        if (Username != "" && HttpContext.Current.Session["logout"] == null)
        {
            if (Username.LastIndexOf("\\") >= 0)
            {
                Username = Username.Substring(Username.LastIndexOf("\\") + 1);

            }


            PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);

            List<Persons> lstNew = objPersonsDB.getPersonsByBadge(Username);
            lstNew = new List<Persons>(from obj in lstNew where obj.ID == "" select obj);//for employees only


            if (lstNew.Count > 0)
            {
                HttpContext.Current.Session["CurrentPerson"] = lstNew[0];
                return;
            }

        }


        if (HttpContext.Current.Request.Cookies["CurrentPerson"] != null)
        {
            Username = HttpContext.Current.Request.Cookies["CurrentPerson"].Value;

           
            PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);

            List<Persons> lstNew = objPersonsDB.getPersonsByGenID(long.Parse(Username));
            


            if (lstNew.Count > 0)
            {
                HttpContext.Current.Session["CurrentPerson"] = lstNew[0];

               

                return;
            }

        }






    }



    /// <summary>
    /// this function will get the current person from session and if he didn't found it will redirect to login
    /// </summary>
    /// <returns>a persons object with the current logged in person details</returns>
    public static Persons getCurrentPersonAR()
    {
        HttpSessionState st = HttpContext.Current.Session;
        if (st == null)
            return null;
        if (st["CurrentPerson"] == null)
        {
            setPersonsInSession();

            if (st["CurrentPerson"] == null)
            {

                HttpContext.Current.Response.Redirect("LoginAR.aspx");
                return null;
            }
        }
        Persons currentPerson = null;

        try
        {
            currentPerson = (Persons)st["CurrentPerson"];

            PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
            List<Persons> lstPersons = objPersonsDB.getPersonsByGenID(currentPerson.GenID);

            if (lstPersons.Count == 0)
            {
                HttpContext.Current.Response.Redirect("LoginAR.aspx");

            }

            currentPerson = lstPersons[0];

        }
        catch
        {
            HttpContext.Current.Response.Redirect("LoginAR.aspx");
        }






        return currentPerson;

    }



    /// <summary>
    /// this function will get the current person from session and if he didn't found it will redirect to login
    /// </summary>
    /// <returns>a persons object with the current logged in person details</returns>
    public static Persons getCurrentPerson()
    {
        HttpSessionState st = HttpContext.Current.Session;
        if (st == null)
            return null;
        if (st["CurrentPerson"] == null)
        {

            setPersonsInSession();

            if (st["CurrentPerson"] == null)
            {

                HttpContext.Current.Response.Redirect("LoginEN.aspx");
                return null;
            }

            
        }
        Persons currentPerson = null;

        try
        {
            currentPerson = (Persons)st["CurrentPerson"];

            PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
            List<Persons> lstPersons = objPersonsDB.getPersonsByGenID(currentPerson.GenID);

            if (lstPersons.Count == 0)
            {
                HttpContext.Current.Response.Redirect("LoginEN.aspx");

            }

            currentPerson = lstPersons[0];

        }
        catch 
        {
            HttpContext.Current.Response.Redirect("LoginEN.aspx");    
        }






        return currentPerson;

    }




    /// <summary>
    /// this function will convert the secounds value to a good formatted value
    /// </summary>
    /// <param name="secounds">the secounds to convert</param>
    /// <returns>a string of the converted secounds in the format HH:mm:ss</returns>
    public static string setSecounds(long? secounds)
    {
        if (secounds == null)
            return "";

        TimeSpan ts = TimeSpan.FromSeconds(secounds.Value);
        string strRet = ((long)ts.TotalHours).ToString("d2") + ":" + ((long)ts.Minutes).ToString("d2") + ":" + ((long)ts.Seconds).ToString("d2");
        return strRet;
    }


    /// <summary>
    /// this function will convert the duration text to time in secounds
    /// </summary>
    /// <param name="timeSpanText">the text to convert</param>
    /// <returns>the time in secounds (-1 for error)</returns>
    public static long? getSecounds(string timeSpanText)
    {
        if (timeSpanText.Trim() == "")
            return null;

        try
        {
            string[] strNew = timeSpanText.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (strNew.Length > 3)
                return -1;

            long val = 0;

            for (int i = 0; i < strNew.Length; i++)
            {
                long factor = (long)Math.Pow(60, (strNew.Length - i - 1));
                val = val + (long.Parse(strNew[i]) * factor);

            }

            return val;


        }
        catch
        {
            return -1;
        }
    }


    /// <summary>
    /// this function will resize the image and add the color to back ground
    /// </summary>
    /// <param name="imgNew">the image to resize</param>
    /// <param name="NewWidth">the new width</param>
    /// <param name="NewHeight">the new height</param>
    /// <param name="cr">the color of back</param>
    /// <returns>a resized Image</returns>
    public static System.Drawing.Image resizeImage(System.Drawing.Image imgNew, int NewWidth, int NewHeight, Color cr)
    {
        int w = NewWidth;
        int h = NewHeight;


        


        System.Drawing.Bitmap bmOld = (Bitmap)imgNew;


        if (w == bmOld.Width && h == bmOld.Height)
            return (System.Drawing.Image)bmOld;


        int oldH = bmOld.Height;
        int oldW = bmOld.Width;


        int newH = 0;
        int newW = 0;

        newH = h;
        newW = newH * oldW / oldH;

        if (newW > w)
        {
            newW = w;
            newH = newW * oldH / oldW;
        }




        Bitmap bmNew = new Bitmap(w, h);
        bmNew.SetResolution(bmOld.HorizontalResolution, bmOld.VerticalResolution);
        Graphics grdNew = Graphics.FromImage((System.Drawing.Image)bmNew);

        grdNew.CompositingQuality = CompositingQuality.HighQuality;
        grdNew.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grdNew.SmoothingMode = SmoothingMode.HighQuality;

        grdNew.FillRectangle(new SolidBrush(cr), new Rectangle(0, 0, w, h));

        grdNew.DrawImage((System.Drawing.Image)bmOld, new RectangleF(0 + ((w - newW) / 2), 0 + ((h - newH) / 2), newW, newH));



        grdNew.Dispose();


        return (System.Drawing.Image)bmNew;
    }
}
